package com.boomshake.controller;

import com.boomshake.common.Result;
import com.boomshake.dto.AdminLoginRequest;
import com.boomshake.service.AdminUserService;
import com.boomshake.utils.JwtUtil;
import com.boomshake.vo.AdminLoginResponseVO;
import com.boomshake.vo.AdminUserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 管理员Controller
 *
 * @author BoomShake
 * @date 2024-12-15
 */
@Slf4j
@RestController
@RequestMapping("/admin")
@CrossOrigin(origins = {"http://localhost:5173", "http://localhost:5174", "http://127.0.0.1:5173", "http://127.0.0.1:5174"}, allowCredentials = "true", maxAge = 3600)
public class AdminController {

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public Result<AdminLoginResponseVO> login(@Valid @RequestBody AdminLoginRequest request,
                                             HttpServletRequest httpRequest) {
        try {
            String clientIp = getClientIp(httpRequest);
            log.info("管理员登录请求，用户名: {}, IP: {}", request.getUsername(), clientIp);
            
            AdminLoginResponseVO response = adminUserService.login(request, clientIp);
            return Result.success("登录成功", response);
        } catch (Exception e) {
            log.error("管理员登录失败", e);
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 获取管理员信息
     */
    @GetMapping("/info")
    public Result<AdminUserInfoVO> getAdminInfo(HttpServletRequest request) {
        try {
            Long adminId = getCurrentAdminId(request);
            AdminUserInfoVO adminInfo = adminUserService.getAdminUserInfo(adminId);
            return Result.success(adminInfo);
        } catch (Exception e) {
            log.error("获取管理员信息失败", e);
            return Result.error("获取管理员信息失败：" + e.getMessage());
        }
    }

    /**
     * 管理员登出
     */
    @PostMapping("/logout")
    public Result<?> logout() {
        // 由于使用JWT无状态认证，登出只需要前端删除token即可
        return Result.success("登出成功");
    }

    /**
     * 从请求中获取当前管理员ID
     */
    private Long getCurrentAdminId(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        String token = jwtUtil.getTokenFromHeader(authHeader);
        
        if (token == null || !jwtUtil.validateToken(token)) {
            throw new RuntimeException("token无效");
        }
        
        return jwtUtil.getUserIdFromToken(token);
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        
        return request.getRemoteAddr();
    }
} 